<?php
namespace removeData;
use removeData\lib\Rconfig;
use removeData\lib\Rlog;
use think\Facade;
use think\facade\Cache;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Hook;

class RemoveData extends Command{
	protected function configure()
	{
		$this->setName('removedata')
			->addArgument('i', Argument::OPTIONAL, "i");
	}
	protected function execute(Input $input, Output $output){
		try{
			//初始化
			$this->init();

			
			//先去处理数据
			$myprocess = new Myprocess();
			$count = $myprocess->count();

			if($count <= 0){
				echo 'no data....';exit;
			}
			$path = dirname(dirname(__DIR__)) . "/think";

			$num = ceil($count/Rconfig::$config['limit']);
			echo 'star threading num:'.$num . PHP_EOL;
			for($i = 0 ; $i < $num ; $i ++) {
				//触发程序
				$str = "php $path insertdata $i";
				$process = new \think\Process($str);
				$process->start(function($type,$data){
					// dump($type);
					// dump($data);
				});
				//$process->wait();
				//$process->getErrorOutput();
			}
			//系统检测
			while(true){
				if(Cache::get('insert_page')>= $num){
					echo 'insert data success...'.PHP_EOL;
					echo 'to do hookAfterProcess...'.PHP_EOL;
					//echo '正在处理导入之后的数据';
					if(method_exists($myprocess,'hookAfterProcess')){
						call_user_func([$myprocess,'hookAfterProcess'],[]);
					}
					Hook::listen('hook_after_process',[]);
					echo 'finally process successful ...'.PHP_EOL;
					break;
				}else{
					sleep(1);
				}
			}
			//加载配置项
//			$this->loadConfig();
		}catch(\Exception $e){
			echo $e->getMessage();
		}

	}

	/*
	* 加载配置
	*/
	public function loadConfig(){
		Rconfig::$config = require(__DIR__ . '/config.php');
	}

	public function init(){
		Cache::rm('insert_page');
		$this->loadConfig();
		//动态注册钩子
		Hook::add('hook_after_process',Rconfig::$config['hook_after_process']);
		//注册自定义日志
		Facade::bind('app\facade\Rlog', '\removeData\lib\Rlog');

	}

}